package com.newgoldcurrency.activities.main;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.navigation.NavigationView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.activities.LoginActivity;
import com.newgoldcurrency.bean.VersionBean;
import com.newgoldcurrency.databinding.ActivityMainBinding;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class
MainActivity extends AppCompatActivity {
    private AppBarConfiguration mAppBarConfiguration;
    private ActivityMainBinding binding;
    private final List<Call> calls=new ArrayList<>();
    @SuppressLint("SetTextI18n")
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.appBarMain.toolbar);
        DrawerLayout drawer = binding.drawerLayout;
        NavigationView navigationView = binding.navView;
        mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_home, R.id.nav_wallet, R.id.nav_chain, R.id.nav_miner, R.id.nav_follow, R.id.nav_invite, R.id.nav_income, R.id.nav_white_paper, R.id.nav_profile, R.id.nav_sign_out, R.id.nav_about).setOpenableLayout(drawer).build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
        binding.appBarMain.mainMenu.setOnClickListener(v -> {
            if (checkDoubleClick()){
                if (binding.drawerLayout.isOpen())binding.drawerLayout.close();
                else binding.drawerLayout.open();
            }
        });
        binding.navView.setNavigationItemSelectedListener(item -> {
            if (item.getTitle().toString().equals("Follow")){
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://goldrr.com/?follow/")));
                return false;
            }else if(item.getTitle().toString().equals("White Paper")){
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://goldrr.com/?whitepaper/")));
                return false;
            }else if (item.getTitle().equals("Sign Out")) {
                HashMap<String, String> map = new HashMap<>();
                map.put("token", App.sp.getString("token", ""));
                Network.post(map, "user/signOut", call -> {
                    call.enqueue(new Callback(){
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            e.printStackTrace();
                        }
                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) {
                            runOnUiThread(() -> {
                                SharedPreferences.Editor edit = App.sp.edit();
                                edit.putString("token", "");
                                edit.apply();
                                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                                finish();
                            });
                        }
                    });
                    calls.add(call);
                });
                return false;
            }else{
                binding.drawerLayout.close();
                navController.navigate(item.getItemId());
                return true;
            }
        });
        String verName="1.0.0";
        int verCode=0;
        try{
            verName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            verCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
        }catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        binding.mainVersion.setText("goldrr.com\nv"+verName);
        HashMap<String, String> map=new HashMap<>();
        map.put("code",String.valueOf(verCode));
        Network.post(map, "homepage/getUpdateInfo", call -> {
            call.enqueue(new Callback(){
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @SuppressLint("SdCardPath")
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                   runOnUiThread(() -> {
                       try {
                           JsonObject jo = JsonParser.parseString(Objects.requireNonNull(response.body()).string()).getAsJsonObject();
                           if (jo.get("message").getAsString().equals("Get updateInfo success")){
                               VersionBean bean = new Gson().fromJson(jo.get("data"), VersionBean.class);
                               try{
                                   int verCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
                                   if (bean.version>verCode){
                                       if (bean.forcedUpdate||!App.sp.getBoolean("notremaining",false)){
                                           Tools.update(MainActivity.this, bean.title, bean.content, bean.forcedUpdate, () -> {
                                               SharedPreferences.Editor edit = App.sp.edit();
                                               edit.putBoolean("notremaining", true);
                                               edit.apply();
                                           }, () -> startActivity(new Intent().setAction("android.intent.action.VIEW").setData(Uri.parse("https://play.google.com/store/apps/details?id=com.newgoldcurrency"))));
                                       }
                                   }
                               }catch (PackageManager.NameNotFoundException e) {
                                   e.printStackTrace();
                               }
                           }else{
                               Tools.toast(jo.get("message").getAsString());
                           }
                       } catch (IOException e) {
                           e.printStackTrace();
                       }
                   });
                }
            });
            calls.add(call);
        });
    }
    @Override
    public boolean onSupportNavigateUp(){
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Call c:calls) c.cancel();
        binding=null;
    }
    private long mClickTime;
    private boolean checkDoubleClick() {
        boolean result= mClickTime < SystemClock.uptimeMillis() - 500;
        mClickTime = SystemClock.uptimeMillis();
        return result;
    }
}